/*
 * Created on 2007-9-14
 *
 * TODO
 */
package jacky.lanlan.song.web.listener.session;

import java.util.*;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import org.apache.log4j.Logger;

/**
 * 利用 HttpSession 的Binding事件来记录日志的Logger。
 * 
 * @author Jacky.Song
 */
public class LogListener implements HttpSessionBindingListener{

	private Logger logger=Logger.getLogger(LogListener.class);

	private String ip;
	private Map<String,String> messages;
	private String boundInfo;
	private String unboundInfo;
	private StringBuilder msgBuf=new StringBuilder();
	private static final String DEFAULT_DIVIDER="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	private String customDivider;
	private long boundTime;
	
	public void setLoggerName(String name) {
		logger=Logger.getLogger(name);
	}
	
	public void setIp(String ip) {
		this.ip = ip;
	}
	
	public void setBoundInfo(String userKind) {
		this.boundInfo = userKind;
	}
	
	public void setUnboundInfo(String privilegeCode) {
		this.unboundInfo = privilegeCode;
	}

	public void setMessages(Map<String, String> messageList) {
		this.messages = messageList;
	}
	
	public void setCustomDivider(String customDivider) {
		this.customDivider = customDivider;
	}
	
	@SuppressWarnings("unused")
	public void valueBound(HttpSessionBindingEvent event) {
		this.boundTime=System.currentTimeMillis();
		this.logMessage(true);
	}
	
	@SuppressWarnings("unused")
	public void valueUnbound(HttpSessionBindingEvent event){
		this.logMessage(false);
	}
	
	private void logMessage(boolean isBound) {
		String divider=customDivider==null?DEFAULT_DIVIDER:customDivider;
		if(logger.isInfoEnabled()) {
			msgBuf.append(isBound?this.boundInfo:this.unboundInfo);
			msgBuf.append(divider);
			msgBuf.append("时间[" +
					String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS", new Date())+"]");
			msgBuf.append(divider);
			msgBuf.append("IP["+ip+"]");
			if(this.messages!=null) {
				for (String mes : this.messages.keySet()) {
					msgBuf.append(divider);
					msgBuf.append(mes+"["+this.messages.get(mes)+"]");
				}
			}
			if(!isBound) {
				msgBuf.append(divider);
				msgBuf.append("持续时间[" + this.calRemainTime(this.boundTime, System.currentTimeMillis()) + "]");
			}
			logger.info(msgBuf.toString());
			msgBuf.delete(0, msgBuf.length());
		}
	}
	
	private String calRemainTime(long start,long end) {
		if(end>start) {
			Calendar c=Calendar.getInstance();
			c.setTimeInMillis(end-start);
			int hour=c.get(Calendar.HOUR_OF_DAY)-8;
			int min=c.get(Calendar.MINUTE);
			int sec=c.get(Calendar.SECOND);
			return hour+":"+min+":"+sec;
		}
		return null;
	}
	
}
